package com.chj.filter;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.chj.dto.BaseResponse;
import com.chj.util.JsonUtil;
import com.netflix.zuul.context.RequestContext;

@Component
@ConfigurationProperties(prefix = "filter.access_token")
@Configuration
public class AccessTokenFilter extends BaseZuulFilter {

	private static Logger logger = LoggerFactory.getLogger(AccessTokenFilter.class);

	@Override
	public String filterType() {
		return getFilterType();
	}

	@Override
	public int filterOrder() {
		return getOrder();
	}

	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();

		Object token = request.getParameter("token");
		token = StringUtils.isEmpty(token) ? request.getHeader("token") : token;

		// 校验token
		if (token == null) {
			logger.info("token为空，禁止访问!");
			ctx.setSendZuulResponse(false);
			ctx.setResponseStatusCode(401);
			ctx.setResponseBody(JsonUtil.getJson(new BaseResponse(HttpStatus.BAD_REQUEST, "token为空!")));
			return null;
		} else {
			// TODO 根据token获取相应的登录信息，进行校验（略）
			logger.info("------------- {}", SecurityContextHolder.getContext().getAuthentication().getName());
			logger.info("------------- {}", JsonUtil.getJson(SecurityContextHolder.getContext().getAuthentication()));
		}

		// 添加Basic Auth认证信
		ctx.addZuulRequestHeader("Authorization", "bearer " + token);

		return null;
	}
}
